package unamur.iodass.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import unamur.iodass.auction.AuctionHandler;
import unamur.iodass.beans.Client;
import unamur.iodass.catalog.RetreiveAllCatalogs;
import unamur.iodass.communication.messages.Book;

import unamur.iodass.forms.ChoixLivreForm;

public class ChoixLivre extends HttpServlet {

	private static final Logger logger = Logger.getLogger(ChoixLivre.class);

	public static final String ATT_BOOKS         = "books";
	public static final String VUE              = "/WEB-INF/choixlivre.jsp";
	public static final String VUE2              = "/OnlineLibrary/choixlivre";

	RetreiveAllCatalogs retreiveAllCatalogs;

	private ArrayList<Book> books;

	public ChoixLivre() {
		retreiveAllCatalogs = RetreiveAllCatalogs.getInstance();
		
	}

	@Override
	public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
		books = retreiveAllCatalogs.getBooksOfLibrary();
		request.setAttribute(ATT_BOOKS, books);

		this.getServletContext().getRequestDispatcher( VUE ).forward( request, response );
	}

	@Override
	public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {

		ChoixLivreForm form = new ChoixLivreForm();

		long isbn = form.retrieveRadioValue(request);

		Book book = retreiveAllCatalogs.getBookByISBN(isbn);

		Client client = form.createClient(request);
		

		AuctionHandler auction = AuctionHandler.getInstance();
		auction.commandeLivre(isbn, client);

		synchronized(auction) {
			while(auction.getProgresses().get(isbn) == true) {
				try {
					auction.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		request.setAttribute("book", book);
		request.setAttribute("client", client);

		this.getServletContext().getRequestDispatcher("/WEB-INF/confirmation.jsp").forward( request, response );

	}

}
